<template>
  <div class="">
    <my-header>
      <span>郑州</span>
    </my-header>
    <my-input v-model="keyword"></my-input>
    <van-button type="primary" @click="search">搜索</van-button>

    <div v-show="list.length == 0 && history.length != 0">
      <h4>历史记录</h4>
      <van-button type="primary" @click="clear">清空</van-button>
      <br />
      <van-tag
        closeable
        size="medium"
        type="primary"
        v-for="(item, index) in history"
        :key="index"
        @click="gotoList(item)"
        @close="close(index)"
      >
        {{ item.name }}
      </van-tag>
    </div>
    <!-- 展示历史记录 -->
    <ul class="list">
      <li v-for="(item, index) in list" :key="index" @click="gotoList(item)">
        {{ item.name }}
      </li>
    </ul>
    <!-- 搜到的结果 -->
  </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import myHeader from "@/components/myHeader.vue";
import myInput from "@/components/myInput.vue";
import { getSearchList } from "../utils/api.js";
//拿到获取搜索列表接口的方法
export default {
  setup(props, ctx) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const data = reactive({
      keyword: "",
      //搜索关键字
      list: [],
      //搜索结果列表
      history: JSON.parse(localStorage.getItem("history")) || [],
    });

    const search = () => {
      getSearchList({ keyword: data.keyword }).then((res) => {
        console.log(res);
        data.list = res;
      });
    };
    //把搜索关键字传到接口进行搜索

    const gotoList = (item) => {
      data.history.forEach((i, index) => {
        if (i.name == item.name) {
          data.history.splice(index, 1);
        }
      });
      //去重 循环 如果有一样的 就把原来的删除

      data.history.splice(4, 1);
      data.history.unshift(item);
      //超过五条的时候删除一条 添加一条
      localStorage.setItem("history", JSON.stringify(data.history));
      //存本地存储

      router.push({
        path: "/list",
        query: {
          title: item.name,
          wd: item.latitude,
          jd: item.longitude,
        },
      });
    };
    //点击跳转到商家列表页面 传三个参数 标题 经度 纬度

    const clear = () => {
      data.history = "";
      localStorage.removeItem("history");
    };
    //清空历史记录

    const close = (index) => {
      data.history.splice(index, 1);
      localStorage.setItem("history", JSON.stringify(data.history));
      //存本地存储
    };
    //删除单条数据
    return { ...toRefs(data), search, gotoList, clear, close };
  },
  components: {
    myHeader,
    myInput,
  },
};
</script>

<style lang="scss" scoped>
.list {
  li {
    height: 40px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    line-height: 40px;
    text-align: center;
  }
}
</style>
